package com.hyh.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.concurrent.Future;

/**
 * @author Summerday
 */

@Service
public class UserService {

    private static final Logger log = LoggerFactory.getLogger(UserService.class);

    public Integer execute1(){
        log.info("execute1");
        // 模拟耗时操作
        sleep(10);
        return 1;
    }

    public Integer execute2(){
        log.info("execute2");
        // 模拟耗时操作
        sleep(5);
        return 2;
    }

    @Async
    public Integer executeAsync1() {
        return this.execute1();
    }

    @Async
    public Integer executeAsync2() {
        return this.execute2();
    }

    @Async
    public Future<Integer> execute01AsyncWithFuture(){
        return AsyncResult.forValue(this.execute1());
    }

    @Async
    public Future<Integer> execute02AsyncWithFuture(){
        return AsyncResult.forValue(this.execute2());
    }

    @Async
    public ListenableFuture<Integer> execute01AsyncWithListenableFuture() {
        try {
            return AsyncResult.forValue(this.execute1());
        } catch (Throwable ex) {
            return AsyncResult.forExecutionException(ex);
        }
    }

    private void sleep(int seconds) {
        try {
            Thread.sleep(seconds * 1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
